package com.cy.server.service.impl;

import com.cy.server.pojo.Admin;
import com.cy.server.pojo.Menu;
import com.cy.server.mapper.MenuMapper;
import com.cy.server.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cy.server.utils.AdminUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author LiShaoZhuo
 * @since 2021-04-26
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {
    @Autowired
    MenuMapper menuMapper;
    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    /**
     * @Description: 根据用户id获取菜单列表
     * @Param:
     * @return:
     * @Author: LiShaoZhuo
     * @Date: 2021/4/29
     */
    @Override
    public List<Menu> getMenusByAdminId() {
        Integer adminId = (AdminUtils.getCurrentAdmin().getId());
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        //从redis获取菜单数据
        List<Menu> menus = (List<Menu>) valueOperations.get("menu_" + adminId);
        //如果菜单列表为空，从数据库获取
        if (CollectionUtils.isEmpty(menus)){
            menus = menuMapper.getMenusByAdminId(adminId);
            //将数据设置到redis中
            valueOperations.set("menu_"+adminId,menus);
        }
        return menus;
    }

    
    /** 
    * @Description: 根据角色获取菜单列表
    * @Param:  
    * @return:  
    * @Author: LiShaoZhuo 
    * @Date: 2021/4/29 
    */
    @Override
    public List<Menu> getMenusWithRole() {
        return menuMapper.getMenusWithRole();
    }

    /**
     * @Description: 查询所有菜单
     * @Param:
     * @return:
     * @Author: LiShaoZhuo
     * @Date: 2021/4/29
     */
    @Override
    public List<Menu> getAllMenus() {
        return menuMapper.getAllMenus();
    }
}
